package com.peng.sell.controller;

import com.peng.sell.exception.SellException;
import com.peng.sell.service.RedisLock;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * 基于Redis的多线程解决线程安全
 */
@Controller
@RequestMapping("/redis")
public class RedisTestController {
    @Autowired
    RedisLock redisLock;

    public static int num = 1000;
    public static int buynum = 0;
    @RequestMapping("/ab")
    public String abTest(Map<String,Object> map){
        String time = String.valueOf(System.currentTimeMillis()+RedisLock.TIMEOUT);
        if(!redisLock.lock("200",time)){
            throw new SellException(101,"人太多啦，一会再来吧");
        }
        num = num-1;
        buynum = buynum+1;
        System.out.println("num:"+num);
        System.out.println("buynum:"+buynum);
        redisLock.unLock("200",time);
        map.put("num",num);
        map.put("buynum",buynum);
        return "redis/ab";
    }


}
